package com.obrempon.credit.market.ui.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.CountDownTimer
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import com.google.android.gms.auth.api.phone.SmsRetriever
import com.obrempon.credit.market.R
import com.obrempon.credit.market.base.app.ObremponActivityStackManager
import com.obrempon.credit.market.common.CommonActivity
import com.obrempon.credit.market.configs.ObremponApiPath
import com.obrempon.credit.market.configs.ObremponApiUrl
import com.obrempon.credit.market.configs.ObremponApiUrl.addCommonParams
import com.obrempon.credit.market.databinding.ObremponCheckMobileActBinding
import com.obrempon.credit.market.event.ObremponEventData
import com.obrempon.credit.market.event.ObremponEventPointHelper
import com.obrempon.credit.market.event.ObremponEventPointType
import com.obrempon.credit.market.request.IHttpCallback
import com.obrempon.credit.market.ui.dialog.ObremponBirthdayDialog
import com.obrempon.credit.market.ui.dialog.ObremponSubmitSuccessDialog
import com.obrempon.credit.market.ui.dialog.ObremponTipsDialog
import com.obrempon.credit.market.utils.helper.ObremponProcessHelper
import com.obrempon.credit.market.utils.log.ObremponLogger
import com.obrempon.credit.market.utils.receiver.ObremponSmsBroadcastReceiver
import com.obrempon.credit.market.utils.shared.ObremponSharedHelper
import com.obrempon.credit.market.utils.shared.ObremponSharedKey
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

/**
 * ObremponCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/11 16:41
 * @Annotation：账号验证页面
 */
class ObremponCheckMobileAct: CommonActivity(){
    lateinit var binding: ObremponCheckMobileActBinding
    private var sendSuccessDialog: ObremponSubmitSuccessDialog? = null
    private var smsBroadcastReceiver: ObremponSmsBroadcastReceiver? = null

    private val SMS_CONSENT_REQUEST = 200
    var eventRemark = ""

    //等待时长
    private var countdownTimer: MyCountDownTimer? = null
    private var countdown = 60

    //选择类型  SMS  、 WHATSAPP
    private var selectType = ""
    //是否需要选择出生日期
    private var needSubmitBirthDay = "NO"
    //出生日期选择
    private var birthdayDialog: ObremponBirthdayDialog? = null
    companion object {
        fun start(context: Context) {
            //当前栈顶是 手机号校验页面 不重复跳转
            if (ObremponActivityStackManager.isCurrentActivity(ObremponCheckMobileAct::class.java)){
                return
            }
            val intent = Intent(context, ObremponCheckMobileAct::class.java)
            context.startActivity(intent)
        }
    }
    override fun takeObremponRootView(): View {
        binding = ObremponCheckMobileActBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initObremponView() {
        eventRemark = "Check Mobile Page"
        setObremponTitleBarVisibility(View.VISIBLE)
        setObremponBackBtnVisibility(View.GONE)
        setObremponTextTitleVisibility(View.GONE)
        setObremponRightBtnRes(R.mipmap.obrempon_customer_icon)
        setBackExit(true)
        rootViewBinding.rootLayout.setBackgroundColor(getColor(R.color.color_ff0569ff))

        initRefreshView()
        showChcekMobileTypeView(false)

        SmsRetriever.getClient(this).startSmsUserConsent(null)
        registerSMSBroadcastReceiver()
    }

    override fun initObremponListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog(eventRemark)
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_CUSTOMER,eventRemark)
        }
        binding.editCode.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                binding.btnSubmit.isEnabled = selectType.isNotEmpty() && takeObremponCheckMobileCode().isNotEmpty()
            }
        })
        binding.editMobile.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                binding.btnConfirm.isEnabled = takeObremponCheckMobile().isNotEmpty()
                binding.textMobile.text = takeObremponCheckMobile()
            }
        })

        //SMS
        binding.smsLayout.setOnClickListener {
            setCheckNumberType("SMS")
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_VERIFICATION_SMS)
        }

        //WhatsApp
        binding.whatsappLayout.setOnClickListener {
            setCheckNumberType("WHATSAPP")
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_VERIFICATION_WHATSAPP)
        }

        binding.btnSend.setOnClickListener {
            if (selectType.isEmpty()){
                return@setOnClickListener
            }
            sendCheckNumberWhatsAppCodeAction()
        }

        binding.imgEdit.setOnClickListener {
           showChcekMobileTypeView(true)
        }
        binding.btnConfirm.setOnClickListener {
            if (takeObremponCheckMobile().isEmpty()){
                return@setOnClickListener
            }
            binding.textMobile.text = takeObremponCheckMobile()
            showChcekMobileTypeView(false)
        }
        //提交
        binding.btnSubmit.setOnClickListener {
            if (takeObremponCheckMobile().isEmpty() || takeObremponCheckMobileCode().isEmpty()){
                binding.btnSubmit.isEnabled = false
                return@setOnClickListener
            }
            onCheckNumberVerificationCodeAction()
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_VERIFICATION_CONTINUE,"${takeObremponCheckMobileCode()}##${takeObremponCheckMobile()}")
        }
    }

    @SuppressLint("SetTextI18n")
    override fun takeObremponData() {
        val zoneCode = ObremponSharedHelper.queryObremponSharedString(ObremponSharedKey.OBREMPON_TIMEZONE_CODE)
        val mobile = ObremponSharedHelper.queryObremponSharedString(ObremponSharedKey.OBREMPON_MOBILE)
        binding.textZoneCode.text = "+$zoneCode"
        binding.textMobile.text = mobile
        binding.editMobile.setText(mobile)

        binding.btnSend.text = getString(R.string.obrempon_button_send)
        binding.btnSend.isEnabled = false
        binding.smsLayout.isEnabled = true
        binding.whatsappLayout.isEnabled = true

        binding.smsLayout.visibility = View.GONE
        binding.whatsappLayout.visibility = View.GONE
        if (ObremponProcessHelper.isObremponAuthCheckSMS()){
            binding.smsLayout.visibility = View.VISIBLE
        }
        if (ObremponProcessHelper.isObremponAuthCheckWhatsApp()){
            binding.whatsappLayout.visibility = View.VISIBLE
        }
        showDefaultCheckTypeView()
        showObremponCheckMobileTipsDialog()
    }

    /**
     * 注册SMS广播接收
     */
    private fun registerSMSBroadcastReceiver(){
        // 2 register receiver
        val intentFilter = IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION)
        smsBroadcastReceiver = ObremponSmsBroadcastReceiver {
            startActivityForResult(it, SMS_CONSENT_REQUEST)
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13 及以上版本使用 receiverFlags 参数
            registerReceiver(
                smsBroadcastReceiver,
                intentFilter,
                SmsRetriever.SEND_PERMISSION,
                null,
                Context.RECEIVER_EXPORTED // 指定导出标志
            )
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Android 8.0 到 Android 12 版本使用带权限的 registerReceiver()
            registerReceiver(
                smsBroadcastReceiver,
                intentFilter,
                SmsRetriever.SEND_PERMISSION,
                null
            )
        } else {
            // Android 8.0 以下版本，只使用 receiver 和 intentFilter 参数
            registerReceiver(
                smsBroadcastReceiver,
                intentFilter
            )
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == SMS_CONSENT_REQUEST) {
            if (resultCode == Activity.RESULT_OK && data != null) {
                // 读取短信内容
                val message = data.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE)
                ObremponLogger.e("Sms content: $message")

                // 提取otp
                val code = extractFirstNumber(message)
                ObremponLogger.e("Sms code: $code")
                if (code != null){
                    binding.editCode.setText(code)
                }
            } else {
                // 用户不同意或没收到待
                ObremponLogger.e("User canceled or no message received")
            }
        }
    }

    /* 初始化刷新 */
    private fun initRefreshView() {
        binding.checkRefreshLayout.setColorSchemeResources(R.color.theme,R.color.purple_500)
        binding.checkRefreshLayout.setOnRefreshListener {
            publishEventData(ObremponEventData(ObremponEventData.TYPE.OBREMPON_PROCESS_REFRESH))
        }
    }

    /**
     * 获取手机号
     */
    fun takeObremponCheckMobile(): String {
        return binding.editMobile.text.toString().trim()
    }

    /**
     * 获取验证码
     */
    fun takeObremponCheckMobileCode(): String {
        return binding.editCode.text.toString().trim()
    }

    /**
     * 切换校验类型
     */
    private fun setCheckNumberType(type: String,isSend: Boolean = true){
        if (selectType == type){
            return
        }
        selectType = type
        showObremponCheckMobileType(type)
        if (isSend){
            sendCheckNumberWhatsAppCodeAction()
        }


    }

    /**
     * 切换是否修改手机号View
     */
    private fun showChcekMobileTypeView(isEdit: Boolean){
        //是否允许修改手机号码
        if (!ObremponProcessHelper.isObremponAuthMobileEditFlag()){
            binding.showMobileLayout.visibility = View.VISIBLE
            binding.imgEdit.visibility = View.INVISIBLE
            binding.showEditLayout.visibility = View.GONE
            return
        }
        when(isEdit){
            true -> {
                binding.showMobileLayout.visibility = View.GONE
                binding.showEditLayout.visibility = View.VISIBLE
                onShowSoftInput(binding.editMobile)
                binding.editMobile.setSelection(takeObremponCheckMobile().length)
            }
            else -> {
                binding.showMobileLayout.visibility = View.VISIBLE
                binding.imgEdit.visibility = View.VISIBLE
                binding.showEditLayout.visibility = View.GONE
            }
        }
    }

    /**
     * 设置默认选中校验类型
     */
    private fun showDefaultCheckTypeView(){
        //设置默认选中：有SMS就选中SMS，否则选中WHATSAPP
        if (ObremponProcessHelper.isObremponAuthCheckSMS()){
            setCheckNumberType("SMS",false)
        } else {
            setCheckNumberType("WHATSAPP",false)
        }
    }

    /**
     * 切换校验类型
     */
    private fun showObremponCheckMobileType(type: String) {
        binding.btnSend.isEnabled = true

        binding.imageSms.setImageResource(R.mipmap.obrempon_check_mobile_send_sms_normal_icon)
        binding.whatsAppTitle.setTextColor(getColor(R.color.color_ffd6d6d6))
        binding.whatsAppSelect.setImageResource(R.mipmap.obrempon_check_mobile_normal_icon)
        binding.whatsappLayout.shapeDrawableBuilder
            .setSolidColor(getColor(R.color.transparent))
            .setStrokeColor(getColor(R.color.color_ffeceff3))
            .setStrokeSize(2)
            .intoBackground()

        binding.imageWhatsApp.setImageResource(R.mipmap.obrempon_check_mobile_send_whatsapp_normal_icon)
        binding.textSms.setTextColor(getColor(R.color.color_ffd6d6d6))
        binding.smsSelect.setImageResource(R.mipmap.obrempon_check_mobile_normal_icon)
        binding.smsLayout.shapeDrawableBuilder
            .setSolidColor(getColor(R.color.transparent))
            .setStrokeColor(getColor(R.color.color_ffeceff3))
            .setStrokeSize(2)
            .intoBackground()
        when(type){
            "SMS" -> {
                binding.textCheckMobileType.text = String.format(getString(R.string.obrempon_check_mobile_type),getString(R.string.obrempon_check_mobile_type_sms))
                binding.imageSms.setImageResource(R.mipmap.obrempon_check_mobile_send_sms_selected_icon)
                binding.textSms.setTextColor(getColor(R.color.color_ff0569ff))
                binding.smsSelect.setImageResource(R.mipmap.obrempon_check_mobile_selected_icon)
                binding.smsLayout.shapeDrawableBuilder
                    .setSolidColor(getColor(R.color.color_fff4f9ff))
                    .setStrokeColor(getColor(R.color.color_ff0569ff))
                    .setStrokeSize(4)
                    .intoBackground()
            }
            else -> {
                binding.textCheckMobileType.text = String.format(getString(R.string.obrempon_check_mobile_type),getString(R.string.obrempon_check_mobile_type_whatsapp))
                binding.imageWhatsApp.setImageResource(R.mipmap.obrempon_check_mobile_send_whatsapp_selected_icon)
                binding.whatsAppTitle.setTextColor(getColor(R.color.color_ff0569ff))
                binding.whatsAppSelect.setImageResource(R.mipmap.obrempon_check_mobile_selected_icon)
                binding.whatsappLayout.shapeDrawableBuilder
                    .setSolidColor(getColor(R.color.color_fff4f9ff))
                    .setStrokeColor(getColor(R.color.color_ff0569ff))
                    .setStrokeSize(4)
                    .intoBackground()
            }
        }
        binding.btnSubmit.isEnabled = takeObremponCheckMobileCode().isNotEmpty()
    }

    /**
     * 验证码发送成功
     * 当为YES时可以跳过，直接调用流程接口，根据流程步骤whatsappFlag标识走
     */
    fun showObremponCheckMobileSendCodeSuccess(directLoginFlag: String) {
        hideObremponLoading()
        when(directLoginFlag){
            "YES" -> {
                showObremponCheckMobileSuccess()
            }
            else -> {
                startCountdownTimer()
            }
        }
    }

    /**
     * 需要选择出生日期
     */
    private fun showObremponCheckMobileChooseBirthdayDialog() {
        if (birthdayDialog == null){
            birthdayDialog = ObremponBirthdayDialog(this,"",object : ObremponBirthdayDialog.IDialogCallback{
                override fun completed(selectDate: JSONObject) {
                    onCheckNumberVerificationCodeAction(selectDate.optString("subDate"))
                }
            })
        }
        birthdayDialog?.show()
    }


    /**
     * 校验成功
     */
    fun showObremponCheckMobileSuccess() {
        ObremponSharedHelper.addObremponSharedData(ObremponSharedKey.OBREMPON_MOBILE, takeObremponCheckMobile())
        publishEventData(ObremponEventData(ObremponEventData.TYPE.OBREMPON_PROCESS_REFRESH))
        if (countdownTimer != null){
            countdownTimer?.cancel()
        }
        finish()
    }

    /**
     * 发送成功提示
     */
    private fun showSendCodeSuccessDialog(){
        if (sendSuccessDialog == null){
            sendSuccessDialog = ObremponSubmitSuccessDialog(this)
            sendSuccessDialog?.setCancelable(true)
            sendSuccessDialog?.setCanceledOnTouchOutside(false)
        }
        sendSuccessDialog?.show()
        sendSuccessDialog?.setTipsSuccessText(getString(R.string.obrempon_check_mobile_send_success_tips))
        launch(Dispatchers.Main){
            delay(2000)
            sendSuccessDialog?.dismiss()
        }
    }

    /**
     * 提示dialog
     */
    private fun showObremponCheckMobileTipsDialog(){
        val tipsDialog = ObremponTipsDialog(this)
        tipsDialog.setCancelable(true)
        tipsDialog.setCanceledOnTouchOutside(true)
        tipsDialog.show()
        tipsDialog.addObremponKindTipsEventRemark(eventRemark)
        tipsDialog.setObremponKindTipsTitleText(getString(R.string.obrempon_dialog_notice))
        tipsDialog.setObremponKindTipsMsgText(getString(R.string.obrempon_check_mobile_dialog_tips))
        tipsDialog.setObremponKintTipsButtonConfirmText(getString(R.string.obrempon_check_mobile_dialog_understand))
        tipsDialog.isObremponKindTipsDoubleButton(false)
    }

    /**
     * 提取连续的数字
     */
    private fun extractFirstNumber(input: String?): String? {
        if(input.isNullOrBlank()) return ""

        val regex = "\\d+".toRegex()
        return regex.find(input)?.value
    }

    class MyCountDownTimer(private val act: ObremponCheckMobileAct, millisInFuture: Int, countDownInterval: Long): CountDownTimer(millisInFuture.toLong(), countDownInterval) {
        override fun onTick(millisUntilFinished: Long) {
            // 这里每隔一段时间（定时器间隔）会被调用
            // 可以在这里更新UI，显示剩余时间
            act.countdown = (millisUntilFinished / 1000).toInt()
            act.showCheckCountdownText()
        }
        override fun onFinish() {
            // 倒计时完成时被调用
            act.showCheckCountdownComplete()
        }
    }

    /**
     * 倒计时
     */
    @SuppressLint("SetTextI18n")
    private fun showCheckCountdownText(){
        binding.btnSend.text = "$countdown S"
    }

    /**
     * 倒计时完成
     */
    private fun showCheckCountdownComplete(){
        countdown = 60
        binding.btnSend.text = getString(R.string.obrempon_button_send)
        binding.btnSend.isEnabled = true
        binding.smsLayout.isEnabled = true
        binding.whatsappLayout.isEnabled = true
        showChcekMobileTypeView(false)
    }

    /**
     * 启动倒计时
     */
    @SuppressLint("SetTextI18n")
    private fun startCountdownTimer() {
        showSendCodeSuccessDialog()
        //随机 60秒 等待时长
        countdown = 60
        binding.btnSend.text = "$countdown S"
        binding.btnSend.isEnabled = false
        binding.smsLayout.isEnabled = false
        binding.whatsappLayout.isEnabled = false
        //手机号码输入框变成不可编辑状态
        binding.showMobileLayout.visibility = View.VISIBLE
        binding.imgEdit.visibility = View.INVISIBLE
        binding.showEditLayout.visibility = View.GONE

        if (countdownTimer == null){
            countdownTimer = MyCountDownTimer(this, countdown * 1000, 1000)
        }
        countdownTimer?.start()
    }

    override fun onObremponPublishEvent(event: ObremponEventData) {
        super.onObremponPublishEvent(event)
        when(event.eventType){
            ObremponEventData.TYPE.OBREMPON_PROCESS_REFRESHED -> {
                hideObremponLoading()
                //需要校验 WhatsApp 或 SMS
                if (!ObremponProcessHelper.isObremponAuthCheckWhatsApp() && !ObremponProcessHelper.isObremponAuthCheckSMS()){
                    //校验成功
                    showObremponCheckMobileSuccess()
                }
            }
            else -> {

            }
        }
    }

    override fun hideObremponLoading() {
        super.hideObremponLoading()
        binding.checkRefreshLayout.isRefreshing = false
    }

    /**
     * 发送WhatsApp验证码
     */
    private fun sendCheckNumberWhatsAppCodeAction(){
        //发送验证，埋点增加手机号
        ObremponEventPointHelper.addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_VERIFICATION_GETCODE,takeObremponCheckMobile())
        showObremponLoading()
        val loginMobile = ObremponSharedHelper.queryObremponSharedString(ObremponSharedKey.OBREMPON_MOBILE)
        val params = JSONObject().addCommonParams().apply {
            put("path", ObremponApiPath.OBREMPON_PATH.OBREMPON_API_WHATSAPP_SEND_CODE_PATH)
            put("mobile", loginMobile)
            put("submitMobile", takeObremponCheckMobile())
            put("sendType",selectType)
        }
        val httpUrl = ObremponApiUrl.queryEasyHttpUrl()
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null) {
                    //是否需要验证生日
                    if (obj.has("needSubmitBirthDay")){
                        needSubmitBirthDay = obj.optString("needSubmitBirthDay")
                    }
                    //当为YES时可以跳过，直接调用流程接口，根据流程步骤whatsappFlag标识走
                    val directLoginFlag = obj.optString("directLoginFlag")
                    showObremponCheckMobileSendCodeSuccess(directLoginFlag)
                }
            }

            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideObremponLoading()
            }
        })
    }

    /**
     * 校验验证码
     */
    fun onCheckNumberVerificationCodeAction(submitBirthDay: String = ""){
        //需要提交出生日期
        if (needSubmitBirthDay == "YES" && submitBirthDay.isEmpty()){
            showObremponCheckMobileChooseBirthdayDialog()
            return
        }
        showObremponLoading()
        val loginMobile = ObremponSharedHelper.queryObremponSharedString(ObremponSharedKey.OBREMPON_MOBILE)
        val params = JSONObject().addCommonParams().apply {
            put("path", ObremponApiPath.OBREMPON_PATH.OBREMPON_API_WHATSAPP_CHECK_CODE_PATH)
            put("mobile", loginMobile)
            put("submitMobile", takeObremponCheckMobile())
            put("code",takeObremponCheckMobileCode())
            put("checkType",selectType)
            put("needSubmitBirthDay",needSubmitBirthDay)//是否需要验证生日
        }
        if (needSubmitBirthDay == "YES" && submitBirthDay.isNotEmpty()){
            params.put("submitBirthDay",submitBirthDay)//出生日期
        }
        val httpUrl = ObremponApiUrl.queryEasyHttpUrl()
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                hideObremponLoading()
                showObremponCheckMobileSuccess()
            }

            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideObremponLoading()
            }
        })
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_VERIFICATION_SMS_START, eventRemark)
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(ObremponEventPointType.PAGE.OBREMPON_PAGE_VERIFICATION_SMS_END, eventRemark)
        if (countdownTimer != null){
            countdownTimer?.cancel()
            countdownTimer = null
        }
        if (smsBroadcastReceiver != null){
            unregisterReceiver(smsBroadcastReceiver)
        }
    }
}